<?php
namespace juven\libs {
    \defined( '_JEXEC' ) or die( 'Restricted access' );
    
    abstract class Model {
        const EVENT_onModelRun  = "event_onModelRun";
        
        protected $_className  = \NULL;
        protected $_childClass = \NULL;

        /** @var String The Database Table name */
        protected $_tableName = \NULL;

        /** @var DatabaseAdapter The Database Object */
        protected $_db = \NULL;

        abstract protected function _init();
        public function __construct() {
            $this->_className  = __CLASS__;
            $this->_childClass = \get_called_class();
            
            $dtp               = new \stdClass();
            $dtp->className    = $this->_className;
            $dtp->childClass   = $this->_childClass;
            juven::eventsManager()->publish(self::EVENT_onModelRun, $dtp);
            
            $this->_db         = juven::dataBase();
            $this->_init();
        }

        protected function getAll_Records() {
            return $this->_db->select("SELECT * FROM `$this->_tableName`");
        }

        /**
         * @param String $field The column name of a table in a database
         */
        protected function getAllRecords_By($field) {
            return $this->_db->select("SELECT `$field` FROM `$this->_tableName`");
        }

        /**
         * @param String $field
         * @param String $value
         */
        protected function getSingleRecord_By($field, $value) {
            return $this->_db->select("SELECT * FROM `$this->_tableName` WHERE `$field` = :v LIMIT 1", array(':v' => $value));
        }

        /**
         * @param String $field
         * @param String $value
         * @return boolean 
         */
        protected function recordExists($field, $value) {
            if ($this->getSingleRecord_By($field, $value)) {
                return \TRUE;
            }
            return \FALSE;
        }

        /**
         * @param array $data
         * @return integer
         */
        protected function create($data) {
            return $this->_db->insert($this->_tableName, $data);
        }

        /**
         * @param array $data An associative array
         * @param string $where the WHERE query part
         */
        protected function update($data, $where) {
            return $this->_db->update($this->_tableName, $data, $where);
        }

        /**
         * @param string $where the WHERE query part
         */
        protected function delete_All($where) {
            return $this->_db->delete_all($this->_tableName, $where);
        }

        /**
         * @param string $where the WHERE query part
         */
        protected function delete_SingleRecord($where) {
            return $this->_db->delete($this->_tableName, $where, 1);
        }
    }
}
?>